<template>
    <div class="DeailEdit">
        <el-upload class="avatar-uploader" action="none" :auto-upload="false" :on-change="addImage"
            :show-file-list="false">
            <el-image v-if="ifimageUrl" :src="Url" class="avatar" ref="img" fit="cover"></el-image>
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            <span v-if="!ifimageUrl">上传文章头图</span>
        </el-upload>
        <el-input type="text" placeholder="输入标题" v-model="title" maxlength="20" show-word-limit ref="title"></el-input>
        <el-input type="text" placeholder="输入副标题（描述）" v-model="digest" maxlength="50" show-word-limit></el-input>
        <Tinymce @TEXT="TEXT" class="Tinymce" :editText="editText"></Tinymce>
        <div class="time">
            <span>创建时间</span>
            <el-date-picker v-model="time" type="datetime" placeholder="不选择默认为当前时间">
            </el-date-picker>
        </div>
        <div class="four">
            <span>选择板块</span>
            <el-select v-model="one_source" placeholder="请选择" ref="sel">
                <el-option v-for="item in options" :key="item" :label="item" :value="item">
                </el-option>
            </el-select>
        </div>
        <div class="tag">
            <div class="haveChice">
                <span>已选标签</span>
                <div class="hadTag">
                    <el-tag closable v-for="val in addTags" :key="val" type="success" @close="handleClose(val)">{{ val }}
                    </el-tag>
                    <div class="number">{{ length }}/3</div>
                </div>
            </div>
            <div class="canChice">
                <span>可选标签</span>
                <div class="canTag">
                    <el-tag effect="dark" v-for="val in allTags" :key="val" type="success" size="medium"
                        @click.native="add">{{ val }}
                    </el-tag>
                    <el-input class="input-new-tag" v-if="inputVisible" v-model="inputValue" ref="saveTagInput"
                        size="small" @keyup.native="keyPush" @blur="blurPush" @click.native="showInput">
                    </el-input>
                    <el-button v-else class="button-new-tag" size="small" @click="showInput" type="success">+ New Tag
                    </el-button>
                </div>

            </div>
        </div>
        <el-button class="post" @click.native="post" type="primary" v-if="!ifEdit">提交</el-button>
        <el-button class="post" @click.native="save" type="primary" v-if="ifEdit">保存</el-button>
    </div>
</template>

<script>
export default {
    name: 'DeailEdit',
    props:['config'],
    data() {
        return {
            Url: ' ',
            ifimageUrl: false,
            content: '',
            title: '',
            digest: '',
            time: '',
            options: ['十年', '生死', '抉择', '铭刻'],
            one_source: '',
            addTags: [],
            length: 0,
            allTags: [],
            inputVisible: false,
            inputValue: '',
            uploadFile: [],
            editText:'',
            ifEdit:false,
            edit_id:null
        };
    },
    beforeCreate() {
        //获取二级标签
        this.$store.dispatch('personalCenter/reqGetTwoSource').then((result) => {
            this.allTags = result.data.arr.split(',')
        })
    },
    methods: {
        //富文本获取
        TEXT(text) {
            this.content = text
        },
        //标签处理开始
        handleClose(tag) {
            this.addTags.splice(this.addTags.indexOf(tag), 1);
            this.allTags.push(tag)
        },
        add(event) {
            if (this.length === 3) {
                this.$message({
                    message: '最多添加三个',
                    type: 'error'
                })
                return
            }
            let tag = event.target.innerText
            if (this.allTags == null) this.allTags = []
            this.allTags.splice(this.allTags.indexOf(tag), 1);
            this.addTags.push(tag)
        },
        showInput() {
            this.inputVisible = true;
            this.$nextTick(() => {
                this.$refs.saveTagInput.$refs.input.focus();
            });
        },
        keyPush(event) {
            if (event.keyCode == 13) {
                this.inputVisible = false;
                this.allTags.push(this.inputValue)
                this.inputValue = ''
            }
        },
        blurPush() {
            if (this.inputValue != '') {
                this.inputVisible = false;
                this.allTags.push(this.inputValue)
                this.inputValue = ''
            }
        },
        //标签处理结束

        //头图上传
        addImage(file, fileList) {
            if (!file.raw.type.startsWith('image')) {
                this.$message({
                    message: '请上传图片文件',
                    type: 'error'
                })
                return;
            }
            if (file.raw.size / 1024 / 1024 > 1.5) {
                this.$message({
                    message: '图片大小不能超过1.5M',
                    type: 'error'
                })
                return;
            }
            this.ifimageUrl = true
            fileList.length = 0;
            fileList.push(file);
            this.uploadFile = [file]
            //本地解析
            FileReader.prototype.VueThis = this;
            let read = new FileReader();
            read.readAsDataURL(file.raw);
            read.onload = function () {
                read.VueThis.Url = this.result
                delete FileReader.prototype.VueThis
            }
        },
        //发送
        post() {
            //其他资源
            if (this.one_source == '' || this.title == '') {
                this.$message({
                    message: '请填写必填项',
                    type: 'error'
                })
                this.$refs.sel.$refs.reference.$refs.input.classList.add('red')
                this.$refs.title.$refs.input.classList.add('red')
                return;
            }
            let obj = {
                title: this.title,
                digest: this.digest,
                content: this.content,
                create_time: this.time ? this.time.toLocaleString().replaceAll('/', '-') : new Date().toLocaleString().replaceAll('/', '-'),
                one_source: this.one_source,
                two_source: this.addTags.toString()
            }

            //two_source 发送
            this.$store.dispatch('personalCenter/reqTwoSource', this.addTags.toString());
            //主体发送
            this.$store.dispatch('personalCenter/reqOtherSource', obj).then((result) => {
                if (this.uploadFile.length != 0) {
                    //如果上传图篇则发送图片
                    let formData = new FormData();
                    formData.append('file', this.uploadFile[0].raw)
                    return this.$store.dispatch('personalCenter/reqImageSource', { formData, article_id: result.data.article_id })
                } else {
                    //如果未上传图片则使用默认图片
                    return this.$store.dispatch('personalCenter/reqUseDefaultImg', { article_id: result.data.article_id })
                }

            }).then((result) => {
                if (result.data.status == '200') {
                    this.$message({
                        message: '发布成功',
                        type: 'success',
                        onClose: () => {
                            location.reload();
                        }
                    })
                } else {
                    this.$message({
                        message: '服务器错误',
                        type: 'error',
                    })
                }
            })

        },
        //编辑状态下的保存
        save(){
            if (this.one_source == '' || this.title == '') {
                this.$message({
                    message: '请填写必填项',
                    type: 'error'
                })
                this.$refs.sel.$refs.reference.$refs.input.classList.add('red')
                this.$refs.title.$refs.input.classList.add('red')
                return;
            }
            let obj = {
                title: this.title,
                digest: this.digest,
                content: this.content,
                create_time: this.time ? this.time.toLocaleString().toString().replaceAll('/', '-') : new Date().toLocaleString().toString().replaceAll('/', '-'),
                one_source: this.one_source,
                two_source: this.addTags.toString(),
                article_id:this.edit_id
            }
            this.$store.dispatch('personalCenter/reqTwoSource', this.addTags.toString());
            //发送资源
            this.$store.dispatch('personalCenter/reqSaveOtherSource', obj).then((result)=>{
                if(result.data.status == '200'){
                    //发送图片
                    if(this.uploadFile[0]){
                        let formData = new FormData();
                        formData.append('file', this.uploadFile[0].raw)
                        return this.$store.dispatch('personalCenter/reqSaveImageSource',  { formData, article_id: this.edit_id });   
                    }else{
                        return new Promise((res,rej)=>{
                            res(result)
                        })
                    }
                }
            }).then((result) => {
                if (result.data.status == '200') {
                    this.$message({
                        message: '保存成功',
                        type: 'success',
                        onClose: () => {
                            window.close();
                        }
                    })
                } else {
                    this.$message({
                        message: '服务器错误',
                        type: 'error',
                    })
                }
            })
        }
    },
    watch: {
        addTags(newValue, oldValue) {
            this.length = newValue.length
        },
        one_source(newValue, oldValue) {
            if (this.one_source !== '') {
                this.$refs.sel.$refs.reference.$refs.input.classList.remove('red')
            }
        },
        title(newValue, oldValue) {
            if (this.title !== '') {
                this.$refs.title.$refs.input.classList.remove('red')
            }
        },
        //编辑填充
        config(newValue, oldValue){
            if(newValue){
                this.content = newValue.content
                this.editText = newValue.content.slice()
                this.title = newValue.title
                this.digest = newValue.digest
                this.Url = newValue.image_url
                this.ifimageUrl = true
                this.one_source = newValue.one_source
                if(newValue.two_source.length !== 0){
                    let arr = newValue.two_source.split(',')
                    arr.forEach(element => {
                        this.addTags.push(element)
                    });
                }
                this.time = newValue.create_time
                this.ifEdit = true;
                this.edit_id = newValue.article_id
            }
        },
    },
}
</script>

<style lang="less">
  .DeailEdit{
    span{
      font-family:'FZZYJT' ;
      user-select: none;
    }
    display: flex;
    justify-content: center;
    align-items: flex-start;
    flex-direction: column;
    width: 80%;
    height: 80%;
    margin: 0 auto;
    position: relative;
    .el-upload{
        overflow: hidden;
      .el-image{
        height: 400px;
      }
    }
    .el-input{
      margin-top:10px ;
      .red{
        border-color:red ;
      }
    }
    .Tinymce{
      margin-top:10px ;
    }
    .time{
      display: flex;
      align-items: center;
      &>span{
        transform: translateY(5px)
      }
      .el-input{
        margin-left:20px ;
      }
    }
    .four{
      height: 60px;
      line-height: 60px;
      width: 100%;
      .el-select{
        margin-left: 20px;
      }
      .el-input{
        .red{
          border-color:red ;
        }
      }
    }

    .tag{
      &>div{
        margin-top:10px ;
        margin-bottom:10px ;
      }
      .haveChice{
        height: 60px;
        display: flex;
        align-items: center;
        .hadTag{
          height: 40px;
          width: 600px;
          border: 2px solid #e5e7eb;;
          border-radius:2em ;
          margin-left:20px ;
          display: flex;
          align-items: center;
          position: relative;
          .el-tag{
            margin-left:20px ;
            font-size: 18px
          }
          .number{
            display: inline-block;
            position: absolute;
            right: 15px;
          }
        }
      }
      .canChice{
        display: flex;
        .canTag{
          width: 400px;
          margin-left:20px ;
          .el-tag{
            margin: 5px 5px;
            margin-top:0px;
            cursor: pointer; 
          }
          .button-new-tag{
            margin-left:5px ;
            span{
              color: white;
            }
          }
          .input-new-tag{
            margin-top:0px ;
            margin-left:5px ;
            width: 80px;
            display: block;
          }
        }
      }
    }
    .avatar-uploader {
      width: 100%;
      .el-upload {
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
        display: flex;
        flex-direction: column;
        &:hover{
          border-color: #409EFF;
          color: #409EFF;
        }
        span{
          font-family:'FZZYJT' ;
          color:#8c939d;
          transform: translateY(-50px);
        }
        &:hover span,&:hover i{
          color: #409EFF;
        }
      }
    }
    .avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 100%;
      height: 178px;
      line-height: 178px;
      text-align: center;
    }
    .avatar {
      width: 100%;
      height: 178px;
      display: block;
    }
    .post{
      position: absolute;
      right: 0;
      bottom: 0;
      span{
        color: white;
      }
    }
  }
</style>